package com.wj.symbol;

import java.util.HashSet;
import java.util.Set;

/**
 * @author wen.jie
 * @date 2021/8/23 9:25
 */
public class SymbolTable<K, V>{

    protected Node head;

    protected int N;

    protected class Node {
        protected K k;

        protected V v;

        public Node next;

        public Node(K k, V v, Node next){
            this.k = k;
            this.v = v;
            this.next = next;
        }
    }

    public SymbolTable(){
        this.head = new Node(null, null, null);
        this.N = 0;
    }

    public int size(){
        return N;
    }

    public void put(K k, V v){
        Node n = head;

        while (n.next != null){
            n = n.next;
            if (n.k.equals(k)){
                n.v = v;
                return;
            }
        }

        Node newNode = new Node(k, v, null);
        newNode.next = head.next;
        head.next = newNode;
        N++;
    }

    public V remove(K k){
        Node n = head;

        while (n.next != null){
            if(n.next.k.equals(k)){
                V v = n.next.v;
                n.next = n.next.next;
                N--;
                return v;
            }
            n = n.next;
        }
        return null;
    }

    public V get(K k){
        Node n = head;
        while (n.next != null){
            if(n.next.k.equals(k)){
                return n.next.v;
            }
            n = n.next;
        }
        return null;
    }

    public Set<K> keySet(){
        Set<K> set = new HashSet<>();
        Node n = head;
        while (n.next != null){
            n = n.next;
            set.add(n.k);
        }
        return set;
    }
}
